const { ccclass, menu, requireComponent } = cc._decorator;

@ccclass
@menu('common/AnimatedComponent')
@requireComponent(cc.Animation)
export default class AnimatedComponent extends cc.Component {

    private map: { [key: string]: () => void } = {};

    async playAnimation(name: string) {
        cc.log(`[AnimatedComponent].playAnimation(${name})`);

        return new Promise((resolve, _) => {
            this._doPlay(name, () => {
                resolve(null);
            });
        });
    }

    private _doPlay(name: string, cb: () => void) {
        this.map[name] = cb;
        this.getComponent(cc.Animation).play(name);
    }

    protected frameEvent_OnAnimationEnded(name: string) {
        const cb = this.map[name];
        cc.log(`frameEvent_OnAnimationEnded: ${name}`);
        if (cb) {
            cb();
            delete this.map[name];
        }
    }

}
